<?php

/**
 * Regional Controller.
 *
 * Helpful methods to make Controller.
 *
 * PHP versions 5
 * CAKEPHP versions 2.x
 * 
 * Green CMS - Content Management System and Framework Powerfull by Cakephp
 * Copyright 2012, GREEN GLOBAL CO., LTD (toancauxanh.vn)
 * 
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @author        Technology Lab No.I <tech1@toancauxanh.vn>
 * @link          
 * @package       Regional.Controller
 * @since         Green v 1.0
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('RegionalAppController', 'Regional.Controller');

/**
 * Autocomple in PHP's IDE solution
 * 
 * @property Regional $Regional
 * 
 */
Class RegionalController extends RegionalAppController {

    /**
     * Use model class
     *
     * @var array
     */
    public $uses = array('Regional.Regional', 'Regional.RegionalI18n');

    /**
     * Called after the controller action.  
     *
     * @return void
     */
    public function beforeRender() {
        parent::beforeRender();
        if (in_array($this->request['action'], array('admin_add', 'admin_edit'))) {
            $layouts = $this->Dashboard->get($this->Regional, 'layouts');
            if (empty($layouts)) {
                $layouts = array(null, array_keys($this->Regional->schema()));
            }
            $this->set('_layouts', $layouts);
        }
        if (in_array($this->request['action'], array('admin_import'))) {
            $layouts_import = $this->Dashboard->get($this->Regional, 'layouts_import');
            if (empty($layouts_import)) {
                $layouts = array(null, array_keys($this->Regional->schema()));
            }
            $this->set('_layouts_import', $layouts_import);
        }
        if (in_array($this->request['action'], array('admin_export'))) {
            $layouts_export = $this->Dashboard->get($this->Regional, 'layouts_export');
            if (empty($layouts_export)) {
                $layouts = array(null, array_keys($this->Regional->schema()));
            }
            $this->set('_layouts_export', $layouts_export);
        }
    }

    /**
     * Management data
     *
     * @return void
     */
    public function admin_index() {
        $_paginate = array(
            'order' => array('id' => 'desc'),
            'fields' => array('id')
        );
        $conditions = $this->Dashboard->parseRequest($this->Regional, $_paginate, array('name'));
        $regionals = $this->paginate();

        $this->Dashboard->translateMaps($this->Regional, $regionals);
        $this->Dashboard->toolbar(__d('system', 'Regional management'), array(
            'add' => array('action' => 'add', 'text' => __d('system', 'Add')),
            'import' => array('action' => 'add', 'text' => __d('system', 'Import')),
            'export' => array('action' => 'add', 'text' => __d('system', 'Export')),
            'copy' => array('action' => 'copy', 'text' => __d('system', 'Copy')),
            'edit' => array('action' => 'edit', 'text' => __d('system', 'Edit')),
            'remove' => array('action' => 'removes', 'text' => __d('system', 'Delete'))
        ));
        if (!empty($this->data['Paginate'])) {
            $data = array_merge(array('task' => '', 'id' => array(0)), $this->data['Paginate']);
            switch (strtolower($data['task'])) {
                case 'add': {
                        $this->Dashboard->redirect(array('action' => 'add', $data['id'][0]));
                    }
                case 'import': {
                        $this->Dashboard->redirect(array('action' => 'import', $data['id'][0]));
                    }
                case 'export': {
                        $this->Dashboard->redirect(array('action' => 'export', $data['id'][0]));
                    }
                case 'copy': {
                        $this->Dashboard->redirect(array('action' => 'add', $data['id'][0]));
                    }
                case 'edit': {
                        $this->Dashboard->redirect(array('action' => 'edit', $data['id'][0]));
                    }
                case 'remove': {
                        $this->Dashboard->redirect(array('action' => 'delete', '?' => array('keys' => $data['id'])));
                    }
            }
        }
        $this->set(compact('regionals', '_crumbs', '_toParent'));
    }

    /**
     * Add data
     *
     * @return void
     */
    public function admin_add($id = null) {
        //Get domain
        $_domain = $this->Regional->find('list', array('fields' => 'domain', 'group' => 'domain', 'contain' => array()));
        if ($_domain == array()) {
            $domain = array('default' => 'default');
        } else {
            foreach ($_domain as $key => $value) {
                $domain[$value] = $value;
            }
        }
        $this->set('_domain', $domain);
        $this->Dashboard->exists($this->Regional, $id, false);
        $this->Dashboard->toolbar(__d('system', 'Add new Regional'), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Save')),
            'next' => array('action' => 'save', 'text' => __d('system', 'Save & Add New')),
            'apply' => array('action' => 'save', 'text' => __d('system', 'Apply')),
            'cancel' => __d('system', 'Cancel')
        ));
        if ($this->request->is('post')) {
            $this->Regional->create();
            $task = strtolower($this->data['Paginate']['task']);
            if (!$task || $task === 'cancel') {
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } elseif ($this->Regional->save($this->request->data)) {
                $this->setFlash(__d('system', 'The %s has been saved', __d('system', 'Regional')), 'success');
                switch ($task) {
                    case 'next': {
                            $this->redirect($this->request->here(false));
                        }
                    case 'apply': {
                            $this->Dashboard->redirect(array('action' => 'edit', $this->Regional->getInsertID()), false, true);
                        }
                }
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } else {
                $this->setFlash(__d('system', 'The %s could not be saved. Please, try again.', __d('system', 'Regional')), 'error');
            }
        } elseif ($id) {
            $this->request->data = $this->Regional->find('first', array('conditions' => array('Regional.id' => $id), 'recursive' => -1));
        }
        $this->set(compact('id'));
    }

    /**
     * Edit data
     *
     * @return void
     */
    public function admin_edit($id = null) {
        //Get domain
        $_domain = $this->Regional->find('list', array('fields' => 'domain', 'group' => 'domain', 'contain' => array()));
        if ($_domain == array()) {
            $domain = array('default' => 'default');
        } else {
            foreach ($_domain as $key => $value) {
                $domain[$value] = $value;
            }
        }
        $this->set('_domain', $domain);
        $this->Dashboard->exists($this->Regional, $id);
        $this->Dashboard->toolbar(__d('system', 'Edit Regional #%s', $id), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Save')),
            'apply' => array('action' => 'save', 'text' => __d('system', 'Apply')),
            'remove' => array('action' => 'remove', 'text' => __d('system', 'Delete')),
            'cancel' => __d('system', 'Cancel')
        ));
        if ($this->request->is('post')) {
            $task = strtolower($this->data['Paginate']['task']);
            if (!$task || $task === 'cancel') {
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } elseif ($this->Regional->save($this->request->data)) {
                if ($task !== 'remove') {
                    $this->setFlash(__d('system', 'The %s has been updated', __d('system', 'Regional')), 'success');
                }
                switch ($task) {
                    case 'remove': {
                            $this->Dashboard->redirect(array('action' => 'delete', '?' => array('keys' => $id)), false, true);
                        }
                    case 'apply': {
                            $this->redirect($this->request->here(false));
                        }
                }
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } else {
                $this->setFlash(__d('system', 'The %s could not be updated. Please, try again.', __d('system', 'Regional')));
            }
        } else {
            $this->request->data = $this->Regional->find('first', array('conditions' => array('Regional.id' => $id), 'recursive' => -1));
        }

        $this->set(compact('id'));
    }

    /**
     * Delete data
     *
     * @return void
     */
    public function admin_delete() {
        if (empty($this->request->query['keys'])) {
            $this->setFlash(__d('system', 'Select elements should be deleted from the list below!', __d('system', 'Regional')));
        } else {
            $complete = 0;
            $message = null;
            $keys = (array) $this->request->query['keys'];
            foreach ($keys as $key) {
                if (!$this->Regional->delete($key)) {
                    $message = $this->Regional->getMessage();
                    if (!$message) {
                        $message = __d('system', 'Cannot delete row #%s.', $key);
                    }
                    break;
                } else {
                    $complete++;
                }
            }
            if ($message) {
                $message = __d('system', '<br/>The processing has stopped because : <b>%s</b>', $message);
            }
            $this->setFlash(__d('system', 'The %1$s has been deleted %2$s / %3$s rows.', __d('system', 'Regional'), $complete, count($keys)) . $message, 'warning');
        }
        $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
    }

    /**
     * Translate data
     *
     * @return void
     */
    public function admin_translate($id = null, $language = null) {
        $this->Dashboard->exists($this->Regional, $id);
        $this->Dashboard->toolbar(__d('system', 'Translate Regional #%s', $id), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Save')),
            'apply' => array('action' => 'save', 'text' => __d('system', 'Apply')),
            'remove' => array('action' => 'remove', 'text' => __d('system', 'Remove')),
            'cancel' => __d('system', 'Cancel')
        ));
        //Export .po when save translate
        $domain = $this->Regional->find('first', array('conditions' => array('id' => $id), 'fields' => 'domain'));
        $domainTranslator = $domain['Regional']['domain'];
        $languageTrans = Configure::read('Languages');
        foreach ($languageTrans as $key => $value) {
            if ($key == $language) {
                $languageTranslator = $value['locale'];
            }
        }
        $locale = $this->Dashboard->getLocale($language);
        if (empty($locale)) {
            $this->setFlash(__d('system', 'The language code <b>%s</b> does not exist', $language));
        }
        $translateFields = $this->Dashboard->translateFields($this->Regional);
        if (empty($translateFields)) {
            $this->setFlash(__d('system', 'The %s not be configured a multilingual', __d('system', 'Regional')));
        }
        if (empty($locale) || empty($translateFields)) {
            $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
        }
        $this->Regional->locale = $locale;
        if ($this->request->is('post')) {
            $task = strtolower($this->data['Paginate']['task']);
            if (!$task || $task === 'cancel') {
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } elseif ($this->Regional->translate($this->request->data)) {
                if ($task !== 'remove') {
                    $this->setFlash(__d('system', 'The %s has been translated', __d('system', 'Regional')), 'success');
                } else {
                    $this->Dashboard->removeTranslated($this->Regional);
                    $this->setFlash(__d('system', 'The translated data of %s has been removed', __d('system', 'Regional')), 'success');
                }
                switch ($task) {
                    case 'remove':
                    case 'apply': {
                            $this->redirect($this->request->here(false));
                        }
                }
                //Export data translator
                $this->redirect(array('action' => 'exportTranslator', $domainTranslator, $languageTranslator));
                //$this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } else {
                $this->setFlash(__d('system', 'The %s could not be translated. Please, try again.', __d('system', 'Regional')));
            }
        }
        $user = $this->Dashboard->getTranslated($this->Regional, $translateFields);

        //return exportTranslator($domainTranslator,$languageTrans);
        $this->set(compact('locale', 'language', 'user', 'id'));
    }

    /**
     * Import data
     *
     * @return void
     */
    public function admin_import() {
        $this->Dashboard->toolbar(__d('system', 'Import new Regional'), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Import')),
            'cancel' => __d('system', 'Cancel')
        ));
        //Get language
        $languages = Configure::read('Languages');
        foreach ($languages as $key => $value) {
            $_language[$value['locale']] = $value['name'];
        }
        $this->set('_language', $_language);
        if ($this->request->is('post')) {
            $task = strtolower($this->data['Paginate']['task']);
            if (!$task || $task === 'cancel') {
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } else {
                if ($this->data['Regional']['data']['tmp_name'] == '') {
                    $this->setFlash(__d('system', 'The %s could not be imported. Please, try again.', __d('system', 'Regional')), 'error');
                } else {
                    $path = $this->data['Regional']['data']['tmp_name'];
                    //debug($path);exit;
                    $file_name = $this->data['Regional']['data']['name'];
                    $info = pathinfo($file_name);
                    $domain = basename($file_name, '.' . $info['extension']);
                    $content = file_get_contents($path);
                    $content = str_replace("msgid \"\"\nmsgstr \"\"", '', $content);

                    file_put_contents($path, $content);

                    $imported = 0;
                    $imports = I18n::loadPo($path);
                    //debug($imports);exit;
                    foreach ($imports as $msgid => $msgstr) {
                        if (!empty($msgid)) {
                            $entryId = false;
                            $exists = $this->Regional->find('first', array(
                                'conditions' => array(
                                    'Regional.name' => $msgid
                                )
                                    )
                            );

                            // imported
                            if (!$exists) {
                                $save = array(
                                    'Regional' => array(
                                        'name' => $msgid,
                                        'domain' => $domain
                                    )
                                );

                                $this->Regional->create($save);

                                if ($new = $this->Regional->save()) {
                                    $importId = $new['Regional']['id'];
                                    $imported++;
                                }
                            } else {
                                $importId = $exists['Regional']['id'];
                            }

                            if ($importId && !empty($msgstr)) {
                                $conditions = array(
                                    'foreign_key' => $importId,
                                    'model' => 'Regional',
                                    //config language
                                    'locale' => $this->data['Regional']['language'],
                                    'field' => 'name'
                                );
                                $i18nExists = $this->RegionalI18n->find('first', array(
                                    'conditions' => $conditions
                                        )
                                );

                                if ($i18nExists) {
                                    $i18nExists['content'] = $msgstr;
                                    $this->RegionalI18n->save($i18nExists);
                                } else {
                                    $conditions['content'] = $msgstr;
                                    $this->RegionalI18n->create($conditions);
                                    $this->RegionalI18n->save();
                                }
                            }
                        }
                    }
                    $this->setFlash(__d('system', '%s importes has been imported.', __d('system', 'Regional')), 'success');
                    $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
                }
            }
        }
    }

    /**
     * Export data
     *
     * @return void
     */
    public function admin_export() {
        $this->Dashboard->toolbar(__d('system', 'Export new Regional'), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Export')),
            'cancel' => __d('system', 'Cancel')
        ));
        //Get language
        $languages = Configure::read('Languages');
        foreach ($languages as $key => $value) {
            $_language[$value['locale']] = $value['name'];
        }
        $this->set('_language', $_language);

        //Get domain
        $_domain = $this->Regional->find('list', array('fields' => 'domain', 'group' => 'domain', 'contain' => array()));
        foreach ($_domain as $key => $value) {
            $domain[$value] = $value;
        }
        $this->set('_domain', $domain);
        if ($this->request->is('post')) {
            $task = strtolower($this->data['Paginate']['task']);
            if (!$task || $task === 'cancel') {
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } else {
                $languageExports = $this->request->data['Regional']['language'];
                $domainExports = $this->request->data['Regional']['domain'];
                $exportsId = $this->Regional->find('all', array('conditions' => array('Regional.domain' => $domainExports)));
                $fileExports = Inflector::underscore("{$domainExports}") . '.pot';
                $output = "# LANGUAGE translation of CakePHP Application\n";
                $output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
                $output .= "#\n";
                $output .= "#, fuzzy\n";
                $output .= "msgid \"\"\n";
                $output .= "msgstr \"\"\n";
                $output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
                $output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
                $output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
                $output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
                $output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
                $output .= "\"MIME-Version: 1.0\\n\"\n";
                $output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
                $output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
                $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
                foreach ($exportsId as $export) {
                    $msgid = str_replace('"', '\"', $export['Regional']['name']);
                    $msgstr = '';
                    foreach ($export['NameTranslation'] as $exportMsgstr) {
                        if ($exportMsgstr['locale'] == $languageExports) {
                            $msgstr = $exportMsgstr['content'];
                        }
                    }
                    $output .= "msgid \"{$msgid}\"\n";
                    $output .= "msgstr \"{$msgstr}\"\n";
                }
                $pathLanguage = APP . 'Locale' . DS;
                if (!is_dir("$pathLanguage/$languageExports/LC_MESSAGES")) {
                    mkdir("$pathLanguage/$languageExports", 0777);
                    mkdir("$pathLanguage/$languageExports/LC_MESSAGES", 0777);
                }
                $pathFile = APP . 'Locale' . DS . $languageExports . DS . 'LC_MESSAGES' . DS;
                @chmod($pathFile, 0777);
                @chown($pathFile, 'www-data.www-data');
                file_put_contents($pathFile . $domainExports . '.pot', $output);
                file_put_contents($pathFile . $domainExports . '.po', $output);
                $this->viewClass = 'Media';
                $params = array(
                    'id' => $fileExports,
                    'name' => strtolower($domainExports),
                    'download' => true,
                    'extension' => 'pot',
                    'path' => $pathFile
                );
                $this->set($params);
                Cache::clear(false, '_cake_core_');
                $this->setFlash(__d('system', '%s exportes has been exported.', __d('system', 'Regional')), 'success');
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            }
        }
    }

    /**
     * Export data
     *
     * @return void
     */
    public function admin_exportTranslator($domain = null, $language = null) {
        $exportsId = $this->Regional->find('all', array('conditions' => array('Regional.domain' => $domain)));
        $fileExports = Inflector::underscore("{$domain}") . '.pot';
        $output = "# LANGUAGE translation of CakePHP Application\n";
        $output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
        $output .= "#\n";
        $output .= "#, fuzzy\n";
        $output .= "msgid \"\"\n";
        $output .= "msgstr \"\"\n";
        $output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
        $output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
        $output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
        $output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
        $output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
        $output .= "\"MIME-Version: 1.0\\n\"\n";
        $output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
        $output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
        $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
        foreach ($exportsId as $export) {
            $msgid = str_replace('"', '\"', $export['Regional']['name']);
            $msgstr = '';
            foreach ($export['NameTranslation'] as $exportMsgstr) {
                if ($exportMsgstr['locale'] == $language) {
                    $msgstr = $exportMsgstr['content'];
                }
            }
            $output .= "msgid \"{$msgid}\"\n";
            $output .= "msgstr \"{$msgstr}\"\n";
        }
        $pathLanguage = APP . 'Locale' . DS;
        if (!is_dir("$pathLanguage/$language/LC_MESSAGES")) {
            mkdir("$pathLanguage/$language", 0777);
            mkdir("$pathLanguage/$language/LC_MESSAGES", 0777);
        }
        $pathFile = APP . 'Locale' . DS . $language . DS . 'LC_MESSAGES' . DS;
        @chmod($pathFile, 0777);
        @chown($pathFile, 'www-data.www-data');
        file_put_contents($pathFile . $domain . '.pot', $output);
        file_put_contents($pathFile . $domain . '.po', $output);
        $this->viewClass = 'Media';
        $params = array(
            'id' => $fileExports,
            'name' => strtolower($domain),
            'download' => true,
            'extension' => 'pot',
            'path' => $pathFile
        );
        $this->set($params);
        Cache::clear(false, '_cake_core_');
        $this->setFlash(__d('system', '%s has been translated.', __d('system', 'Regional')), 'success');
        $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
    }

    public function admin_clear_cache() {
        foreach (array(CACHE . 'views' . DS, CACHE . 'models' . DS, CACHE . 'persistent' . DS, CACHE . 'i18n' . DS) as $path) {
            $normalFiles = glob($path . '*');
            $hiddenFiles = glob($path . '\.?*');

            $normalFiles = $normalFiles ? $normalFiles : array();
            $hiddenFiles = $hiddenFiles ? $hiddenFiles : array();

            $files = array_merge($normalFiles, $hiddenFiles);
            if (is_array($files)) {
                foreach ($files as $file) {
                    if (preg_match('/(\.|\.\.)$/', $file)) {
                        continue;
                    }
                    if (is_file($file) === true) {
                        @unlink($file);
                    }
                }
            }
        }
        $this->setFlash(__d('system', '%s has been cleared.', __d('system', 'Cache')), 'success');
        $this->redirect($this->referer());
    }

}

?>
